'use client'

import React, { useEffect, useState, useRef } from "react";
import {
  Button,
  Input,
  Spinner,
  Chip,
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
  Checkbox,
  useDisclosure,
  Image,
  Badge,
  Modal,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter
} from "@nextui-org/react";
import { BiArrowBack, BiSave, BiTag, BiUpload, BiX, BiMessageSquare, BiPlus, BiHistory, BiMenu } from "react-icons/bi";
import { FiMessageSquare } from "react-icons/fi";
import { useRouter, useParams } from "next/navigation";
import { MdEditor, ToolbarTips } from 'md-editor-rt';
import 'md-editor-rt/lib/style.css';
import { AuthenticationChecker } from "@/app/config/authenticationChecker";
import ToastUtil from "@/app/utils/toastUtil";
import { useTheme } from "next-themes";
import EmojiSelect from "@/app/components/tools/EmojiSelect";
import createAxiosClient from "@/app/utils/axiosRequest";
import { useTags, TagItem } from "@/app/pages/profile/TagManagement";
import CommentSection from "@/app/components/comment/CommentSection";
import { getCommentCount } from "@/app/service/commentService";
import NoteContent from "@/app/components/note/NoteContent";
import AIPanel from "@/app/components/ai/AIPanel";
import HistoryVersionPanel from "@/app/components/history/HistoryVersionPanel";

interface NoteData {
  id?: number;
  collectionId?: number;
  title: string;
  content: string;
  emoji: string;
  icon?: string;
  isPublic: number;
  tags: TagItem[];
}

export default function NotePage() {
  const router = useRouter();
  const { theme } = useTheme();
  const axiosInstance = createAxiosClient();
  const { getUserTags, createTag } = useTags();
  const params = useParams();

  // 笔记ID和集合ID处理
  const noteId = params.id === "new" ? null : parseInt(params.id);
  const [collectionId, setCollectionId] = useState<number | null>(null);

  // 笔记数据状态
  const [noteData, setNoteData] = useState<NoteData>({
    title: "",
    content: "",
    emoji: "📝",
    isPublic: 0,
    tags: []
  });

  // 界面状态
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  // 标签相关状态
  const [availableTags, setAvailableTags] = useState<TagItem[]>([]);
  const [selectedTagIds, setSelectedTagIds] = useState<Set<number>>(new Set());

  // Emoji选择器
  const { isOpen: isSelectEmoji, onOpen: onOpenSelectEmoji, onOpenChange: onSelectChange } = useDisclosure();

  // 文件上传相关状态
  const [uploading, setUploading] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 编辑器工具栏配置
  const [toolbars] = useState<(keyof ToolbarTips)[]>([
    'bold', 'underline', 'italic', '-',
    'strikeThrough', 'title', 'sub', 'sup', 'quote', 'unorderedList', 'orderedList', '-',
    'codeRow', 'code', 'link', 'image', 'table', 'mermaid', 'katex', '-',
    'revoke', 'next', 'save', '=',
    'pageFullscreen', 'fullscreen', 'preview', 'htmlPreview', 'catalog'
  ]);

  // 评论侧边栏状态
  const [showComments, setShowComments] = useState(false);
  const [commentCount, setCommentCount] = useState(0);

  // AI面板状态
  const [showAIPanel, setShowAIPanel] = useState(false);
  const [showHistoryPanel, setShowHistoryPanel] = useState(false);

  // 新建标签相关状态
  const [newTagName, setNewTagName] = useState<string>("");
  const { isOpen: isOpenCreateTag, onOpen: onOpenCreateTag, onOpenChange: onOpenChangeCreateTag } = useDisclosure();
  const [creatingTag, setCreatingTag] = useState<boolean>(false);

  // 检查用户登录状态
  useEffect(() => {
    async function checkAuth() {
      const [authenticated] = AuthenticationChecker();
      setIsLoggedIn(authenticated);

      if (!authenticated) {
        ToastUtil("请先登录", "❌", "error");
        setTimeout(() => router.push('/'), 1500);
        return;
      }

      // 获取URL参数中的集合ID
      const urlParams = new URLSearchParams(window.location.search);
      const collectionIdParam = urlParams.get('collectionId');
      if (collectionIdParam) {
        setCollectionId(parseInt(collectionIdParam));
      }

      // 加载标签和笔记数据
      await loadTags();

      if (noteId) {
        await loadNoteData(noteId);
      } else {
        setLoading(false);
      }
    }

    checkAuth();
  }, []);

  // 当组件加载时，检查是否有从AI页面过来的内容
  useEffect(() => {
    if (params.id === "new" && window.location.search.includes("fromAI=true")) {
      const aiContent = localStorage.getItem('aiGeneratedContent');
      const aiTitle = localStorage.getItem('aiGeneratedTitle');

      if (aiContent) {
        updateNoteField('content', aiContent);
        localStorage.removeItem('aiGeneratedContent');
      }

      if (aiTitle) {
        updateNoteField('title', aiTitle);
        localStorage.removeItem('aiGeneratedTitle');
      }
    }
  }, [params.id]);

  // 加载标签数据
  const loadTags = async () => {
    const tagsData = await getUserTags(1, 100);
    if (tagsData) {
      setAvailableTags(tagsData.records);
    }
  };

  // 加载笔记数据
  const loadNoteData = async (id: number) => {
    try {
      setLoading(true);
      const response = await axiosInstance.get(`/app/api/v1/notes/${id}`);

      if (response.data.status) {
        const noteDetail = response.data.data;

        // 设置笔记数据
        setNoteData({
          id: noteDetail.id,
          collectionId: noteDetail.collectionId,
          title: noteDetail.title || "",
          content: noteDetail.content || "",
          emoji: noteDetail.emoji || "📝",
          icon: noteDetail.icon || "",
          isPublic: noteDetail.isPublic || 0,
          tags: noteDetail.tags || []
        });

        // 设置选中的标签
        const tagIds = new Set(noteDetail.tags?.map((tag: TagItem) => tag.id) || []);
        setSelectedTagIds(tagIds);

        // 设置集合ID
        if (noteDetail.collectionId) {
          setCollectionId(noteDetail.collectionId);
        }

        // 设置图标预览
        if (noteDetail.icon) {
          setPreviewUrl(noteDetail.icon);
        }

        // 加载评论数
        if (noteDetail.id) {
          loadCommentCount(noteDetail.id);
        }
      } else {
        ToastUtil(response.data.message || "获取笔记失败", "❌", "error");
      }
    } catch (error: any) {
      ToastUtil(error.message || "获取笔记异常", "❌", "error");
    } finally {
      setLoading(false);
    }
  };

  // 加载评论数
  const loadCommentCount = async (noteId: number) => {
    try {
      const response = await getCommentCount(noteId);
      if (response && response.code === 200) {
        setCommentCount(response.data || 0);
      }
    } catch (error) {
      console.error("获取评论数失败:", error);
    }
  };

  // 更新笔记数据字段
  const updateNoteField = (field: keyof NoteData, value: any) => {
    setNoteData(prev => ({ ...prev, [field]: value }));
  };

  // 处理标签选择
  const handleTagSelect = (tagId: number) => {
    const newSelectedTagIds = new Set(selectedTagIds);

    if (newSelectedTagIds.has(tagId)) {
      newSelectedTagIds.delete(tagId);
    } else {
      newSelectedTagIds.add(tagId);
    }

    setSelectedTagIds(newSelectedTagIds);

    // 更新笔记中的标签数据
    const selectedTags = availableTags.filter(tag => newSelectedTagIds.has(tag.id));
    updateNoteField('tags', selectedTags);
  };

  // 处理表情选择
  const handleEmojiSelect = (emoji: string) => {
    updateNoteField('emoji', emoji);
  };

  // 处理图片上传到笔记内容
  const handleImageUpload = async (files: File[], callback: (urls: string[]) => void) => {
    try {
      const uploadPromises = files.map((file) => {
        return new Promise<string>((resolve, reject) => {
          const formData = new FormData();
          formData.append('file', file);

          // 临时业务ID，实际使用时可能需要调整
          const tempBusinessId = 'note-' + Date.now();

          axiosInstance.post(`/middleware/file/upload?businessId=${tempBusinessId}`,
            formData,
            {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }
          ).then(response => {
            const data = response.data;
            if (data.status && data.data) {
              const imageUrl = typeof data.data === 'string' ? data.data : data.data.url;
              resolve(imageUrl);
            } else {
              reject(new Error(data.message || "上传失败"));
            }
          }).catch(error => {
            reject(error);
          });
        });
      });

      const urls = await Promise.all(uploadPromises);
      callback(urls);
    } catch (error: any) {
      ToastUtil(error.message || "图片上传失败", "❌", "error");
      callback([]);
    }
  };

  // 笔记图标上传处理
  const handleIconUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 验证文件类型，只允许图片
    if (!file.type.startsWith('image/')) {
      ToastUtil("请上传图片文件", '❌', "error");
      return;
    }

    // 显示本地预览
    const localPreviewUrl = URL.createObjectURL(file);
    setPreviewUrl(localPreviewUrl);

    // 准备上传
    setUploading(true);

    try {
      // 创建FormData
      const formData = new FormData();
      formData.append('file', file);

      // 业务ID可以是临时ID，等创建成功后再关联
      const tempBusinessId = 'note-icon-' + Date.now();

      // 调用文件上传接口
      const response = await axiosInstance.post(`/middleware/file/upload?businessId=${tempBusinessId}`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      );

      const data = response.data;
      if (data.status && data.data) {
        // 确保只存储URL字符串
        const iconUrl = data.data.url || data.data;
        updateNoteField('icon', iconUrl);
        ToastUtil("图标上传成功", '✅', "success");
      } else {
        ToastUtil(data.message || "上传失败", '❌', "error");
        // 清除预览
        URL.revokeObjectURL(localPreviewUrl);
        setPreviewUrl('');
      }
    } catch (error: any) {
      ToastUtil(error.message || "上传异常", '❌', "error");
      // 清除预览
      URL.revokeObjectURL(localPreviewUrl);
      setPreviewUrl('');
    } finally {
      setUploading(false);
    }
  };

  // 清除已上传的图标
  const clearUploadedIcon = () => {
    updateNoteField('icon', '');
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
      setPreviewUrl('');
    }
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 保存笔记
  const saveNote = async () => {
    if (!noteData.title.trim()) {
      ToastUtil("标题不能为空", "❌", "error");
      return;
    }

    try {
      setSaving(true);

      // 构建API请求参数
      const params = noteId ? {
        id: noteId,
        collectionId, // 可以为null，表示根目录
        title: noteData.title,
        content: noteData.content,
        tagIds: Array.from(selectedTagIds), // 直接发送数字ID数组
        isPublic: noteData.isPublic,
        emoji: noteData.emoji,
        icon: noteData.icon
      } : {
        collectionId, // 可以为null，表示根目录
        title: noteData.title,
        content: noteData.content,
        tagIds: Array.from(selectedTagIds), // 直接发送数字ID数组
        isPublic: noteData.isPublic,
        emoji: noteData.emoji,
        icon: noteData.icon
      };

      // 根据是创建还是更新调用不同的API
      const response = await axiosInstance[noteId ? 'put' : 'post'](
        '/app/api/v1/notes',
        params
      );

      if (response.data.status) {
        ToastUtil(noteId ? "笔记更新成功" : "笔记创建成功", "✅", "success");

        // 如果是新建，重定向到编辑页
        if (!noteId && response.data.data) {
          // 直接从data获取笔记ID，因为接口返回的就是笔记ID
          const newNoteId = response.data.data;
          if (newNoteId) {
            // 用setTimeout确保Toast消息能够显示
            setTimeout(() => {
              router.push(`/note/${newNoteId}${collectionId ? `?collectionId=${collectionId}` : ''}`);
            }, 500);
            return;
          }
        }

        // 刷新数据
        if (noteId) {
          await loadNoteData(noteId);
        }
      } else {
        ToastUtil(response.data.message || (noteId ? "更新失败" : "创建失败"), "❌", "error");
      }
    } catch (error: any) {
      ToastUtil(error.message || "操作异常", "❌", "error");
    } finally {
      setSaving(false);
    }
  };

  // 返回按钮处理
  const handleBack = () => {
    router.push(`/?path=${collectionId || 'root'}`);
  };

  // 处理AI生成的内容
  const handleApplyAIContent = (content: string) => {
    updateNoteField('content', content);
  };

  // 处理AI生成的标题
  const handleApplyAITitle = (title: string) => {
    updateNoteField('title', title);
  };

  // 处理打开新建标签对话框
  const handleCreateNewTag = () => {
    setNewTagName("");
    onOpenCreateTag();
  };

  // 处理创建新标签
  const handleSubmitNewTag = async () => {
    if (!newTagName.trim()) {
      ToastUtil("标签名称不能为空", "❌", "error");
      return;
    }

    setCreatingTag(true);
    const success = await createTag(newTagName);

    if (success) {
      // 重新加载标签列表
      await loadTags();
      onOpenChangeCreateTag(false);
      ToastUtil("新建标签成功", "✅", "success");
    }

    setCreatingTag(false);
  };

  // 如果正在加载，显示加载状态
  if (loading) {
    return (
      <div className="flex h-screen items-center justify-center bg-white dark:bg-default-100">
        <div className="text-center">
          <Spinner size="lg" color="primary" />
          <p className="mt-2 text-gray-500">加载中...</p>
        </div>
      </div>
    );
  }

  if (!noteData) {
    return <div>Note not found</div>;
  }

  return (
    <div className="min-h-screen flex flex-col bg-white dark:bg-default-100">
      {/* 顶部操作栏 */}
      <div className="p-4 flex flex-col md:flex-row items-start md:items-center justify-between bg-gray-50 dark:bg-gray-900 border-b gap-2">
        {/* 标题和图标部分 - 在所有设备上保持一行 */}
        <div className="flex items-center w-full md:w-auto">
          <Button
            isIconOnly
            variant="light"
            className="mr-2"
            onClick={handleBack}
          >
            <BiArrowBack className="text-xl" />
          </Button>

          {/* 表情/图标显示区域 */}
          <div className="flex items-center gap-2">
            {previewUrl ? (
              <div className="relative w-10 h-10 rounded-md overflow-hidden border">
                <Image
                  src={previewUrl}
                  alt="Note icon"
                  className="w-full h-full object-cover"
                />
              </div>
            ) : (
              <div
                className="mx-2 text-3xl cursor-pointer border rounded-md p-1 shadow-sm"
                onClick={onOpenSelectEmoji}
              >
                {noteData.emoji}
              </div>
            )}

            {/* 图标上传按钮 */}
            <div className="flex">
              <Button
                isIconOnly
                size="sm"
                color="primary"
                variant="flat"
                onClick={() => fileInputRef.current?.click()}
                isLoading={uploading}
              >
                <BiUpload />
              </Button>

              {previewUrl && (
                <Button
                  isIconOnly
                  size="sm"
                  color="danger"
                  variant="flat"
                  className="ml-2"
                  onClick={clearUploadedIcon}
                >
                  <BiX />
                </Button>
              )}

              <input
                type="file"
                ref={fileInputRef}
                className="hidden"
                accept="image/*"
                onChange={handleIconUpload}
                disabled={uploading}
              />
            </div>
          </div>

          <Input
            className="w-full md:w-96 ml-2"
            size="sm"
            placeholder="笔记标题"
            value={noteData.title}
            onValueChange={(val) => updateNoteField('title', val)}
          />
        </div>

        {/* 功能按钮区域 - 在移动设备上使用下拉菜单 */}
        <div className="flex items-center gap-2 w-full md:w-auto mt-2 md:mt-0 overflow-x-auto pb-2 md:pb-0 md:overflow-visible">
          {/* 桌面版显示所有按钮 */}
          <div className="hidden md:flex items-center gap-2">
            <Button
              variant={showAIPanel ? "solid" : "flat"}
              color="primary"
              startContent={<BiMessageSquare />}
              onClick={() => {
                setShowAIPanel(!showAIPanel);
                if (!showAIPanel) setShowHistoryPanel(false);
              }}
            >
              AI助手
            </Button>

            {/* 历史版本按钮 - 仅在编辑已有笔记时显示 */}
            {noteId && (
              <Button
                variant={showHistoryPanel ? "solid" : "flat"}
                color="primary"
                startContent={<BiHistory />}
                onClick={() => {
                  setShowHistoryPanel(!showHistoryPanel);
                  if (!showHistoryPanel) setShowAIPanel(false);
                }}
              >
                历史版本
              </Button>
            )}

            <Dropdown>
              <DropdownTrigger>
                <Button
                  variant="flat"
                  color="primary"
                  startContent={<BiTag />}
                >
                  标签 ({selectedTagIds.size})
                </Button>
              </DropdownTrigger>
              <DropdownMenu
                aria-label="标签选择"
                variant="flat"
                closeOnSelect={false}
                selectionMode="multiple"
                selectedKeys={new Set(Array.from(selectedTagIds).map(id => id.toString()))}
                onSelectionChange={(keys) => {
                  if (typeof keys !== 'string') {
                    const newSelectedIds = new Set<number>();
                    keys.forEach((key) => {
                      // 排除"create-new-tag"项
                      if (key !== "create-new-tag") {
                        newSelectedIds.add(parseInt(key.toString()));
                      }
                    });
                    setSelectedTagIds(newSelectedIds);

                    // 更新笔记标签数据
                    const selectedTags = availableTags.filter(tag => newSelectedIds.has(tag.id));
                    updateNoteField('tags', selectedTags);
                  }
                }}
                emptyContent={availableTags.length === 0 ? "没有可用标签，请先创建标签" : null}
              >
                {availableTags.map((tag) => (
                  <DropdownItem key={tag.id.toString()} textValue={tag.name}>
                    <div className="flex items-center gap-2">
                      <Checkbox
                        isSelected={selectedTagIds.has(tag.id)}
                        className="pointer-events-none" // 防止冒泡冲突
                      />
                      <span>{tag.name}</span>
                    </div>
                  </DropdownItem>
                ))}
                <DropdownItem 
                  key="create-new-tag" 
                  textValue="新建标签" 
                  className="text-primary"
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleCreateNewTag();
                  }}
                >
                  <div className="flex items-center gap-2">
                    <BiPlus className="text-primary" />
                    <span>新建标签</span>
                  </div>
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
            
            <Checkbox
              isSelected={noteData.isPublic === 1}
              onValueChange={(checked) => updateNoteField('isPublic', checked ? 1 : 0)}
            >
              公开
            </Checkbox>

            {noteId && (
              <Badge
                content={commentCount > 0 ? commentCount : undefined}
                color="primary"
                isInvisible={commentCount === 0}
                variant="flat"
                shape="circle"
                placement="top-right"
              >
                <Button
                  variant={showComments ? "solid" : "flat"}
                  color="primary"
                  isIconOnly
                  onClick={() => setShowComments(!showComments)}
                  className="mr-2"
                  title={showComments ? "隐藏评论" : "显示评论"}
                >
                  <FiMessageSquare size={20} />
                </Button>
              </Badge>
            )}
          </div>

          {/* 移动设备上显示下拉菜单 */}
          <div className="flex md:hidden items-center gap-2 w-full justify-between">
            <Dropdown>
              <DropdownTrigger>
                <Button
                  variant="flat"
                  color="primary"
                  startContent={<BiMenu />}
                >
                  选项
                </Button>
              </DropdownTrigger>
              <DropdownMenu aria-label="笔记选项">
                <DropdownItem 
                  key="ai"
                  startContent={<BiMessageSquare />}
                  className={showAIPanel ? "text-primary" : ""}
                  onPress={() => {
                    setShowAIPanel(!showAIPanel);
                    if (!showAIPanel) setShowHistoryPanel(false);
                  }}
                >
                  AI助手
                </DropdownItem>
                
                {noteId && (
                  <DropdownItem 
                    key="history"
                    startContent={<BiHistory />}
                    className={showHistoryPanel ? "text-primary" : ""}
                    onPress={() => {
                      setShowHistoryPanel(!showHistoryPanel);
                      if (!showHistoryPanel) setShowAIPanel(false);
                    }}
                  >
                    历史版本
                  </DropdownItem>
                )}
                
                <DropdownItem 
                  key="tags"
                  startContent={<BiTag />}
                  onPress={() => {
                    // 触发标签下拉菜单
                    document.getElementById("mobile-tag-dropdown-trigger")?.click();
                  }}
                >
                  标签 ({selectedTagIds.size})
                </DropdownItem>
                
                {noteId && (
                  <DropdownItem 
                    key="comments"
                    startContent={<FiMessageSquare />}
                    className={showComments ? "text-primary" : ""}
                    onPress={() => setShowComments(!showComments)}
                  >
                    {showComments ? "隐藏评论" : "显示评论"} {commentCount > 0 ? `(${commentCount})` : ""}
                  </DropdownItem>
                )}
                
                <DropdownItem key="public">
                  <Checkbox
                    isSelected={noteData.isPublic === 1}
                    onValueChange={(checked) => updateNoteField('isPublic', checked ? 1 : 0)}
                  >
                    公开
                  </Checkbox>
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
            
            {/* 移动设备上的标签下拉菜单触发器 - 保持隐藏 */}
            <div className="hidden">
              <Dropdown>
                <DropdownTrigger>
                  <Button id="mobile-tag-dropdown-trigger" variant="flat">标签</Button>
                </DropdownTrigger>
                <DropdownMenu
                  aria-label="标签选择"
                  variant="flat"
                  closeOnSelect={false}
                  selectionMode="multiple"
                  selectedKeys={new Set(Array.from(selectedTagIds).map(id => id.toString()))}
                  onSelectionChange={(keys) => {
                    if (typeof keys !== 'string') {
                      const newSelectedIds = new Set<number>();
                      keys.forEach((key) => {
                        // 排除"create-new-tag"项
                        if (key !== "create-new-tag") {
                          newSelectedIds.add(parseInt(key.toString()));
                        }
                      });
                      setSelectedTagIds(newSelectedIds);

                      // 更新笔记标签数据
                      const selectedTags = availableTags.filter(tag => newSelectedIds.has(tag.id));
                      updateNoteField('tags', selectedTags);
                    }
                  }}
                >
                  {availableTags.map((tag) => (
                    <DropdownItem key={tag.id.toString()} textValue={tag.name}>
                      <div className="flex items-center gap-2">
                        <Checkbox
                          isSelected={selectedTagIds.has(tag.id)}
                          className="pointer-events-none"
                        />
                        <span>{tag.name}</span>
                      </div>
                    </DropdownItem>
                  ))}
                  <DropdownItem 
                    key="create-new-tag" 
                    textValue="新建标签" 
                    className="text-primary"
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      handleCreateNewTag();
                    }}
                  >
                    <div className="flex items-center gap-2">
                      <BiPlus className="text-primary" />
                      <span>新建标签</span>
                    </div>
                  </DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </div>
            
            {/* 在所有设备上保持可见的保存按钮 */}
            <Button
              color="primary"
              startContent={<BiSave />}
              isLoading={saving}
              onClick={saveNote}
              className="ml-auto"
            >
              保存
            </Button>
          </div>
          
          {/* 在大屏幕上显示的保存按钮 */}
          <div className="hidden md:block">
            <Button
              color="primary"
              startContent={<BiSave />}
              isLoading={saving}
              onClick={saveNote}
            >
              保存
            </Button>
          </div>
        </div>
      </div>

      {/* 标签显示区域 */}
      {selectedTagIds.size > 0 && (
        <div className="px-4 py-2 bg-gray-50 dark:bg-gray-900 border-b flex flex-wrap gap-1">
          {noteData.tags.map(tag => (
            <Chip
              key={tag.id}
              variant="flat"
              color="primary"
              radius="sm"
              onClose={() => handleTagSelect(tag.id)}
              classNames={{
                base: "h-6"
              }}
            >
              {tag.name}
            </Chip>
          ))}
        </div>
      )}

      {/* 编辑器区域 - 修改侧边栏布局，添加历史版本面板 */}
      <div className="flex-grow flex overflow-hidden border-t border-gray-200 dark:border-gray-700">
        {showAIPanel && (
          <div className="w-[380px] h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 overflow-auto">
            <div className="p-4">
              <AIPanel
                noteId={noteId ? Number(noteId) : undefined}
                noteTitle={noteData.title}
                noteContent={noteData.content}
                onApplyContent={handleApplyAIContent}
                onApplyTitle={handleApplyAITitle}
              />
            </div>
          </div>
        )}

        {showHistoryPanel && noteId && (
          <div className="w-[380px] h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 overflow-auto">
            <div className="p-4">
              <HistoryVersionPanel
                noteId={Number(noteId)}
                onApplyContent={handleApplyAIContent} // 重用AI内容应用的处理函数
              />
            </div>
          </div>
        )}

        <MdEditor
          className="h-full w-full flex-grow border-x border-gray-200 dark:border-gray-700"
          style={{
            height: "calc(100vh - 140px)",
            minHeight: "500px",
            width: (showAIPanel || showHistoryPanel || (showComments && noteId)) ? "calc(100% - 380px)" : "100%"
          }}
          modelValue={noteData.content}
          onChange={(val) => updateNoteField('content', val)}
          toolbars={toolbars}
          showCodeRowNumber={true}
          autoDetectCode={true}
          theme={theme === 'light' ? 'light' : 'dark'}
          preview={true}
          showToolbarName
          onUploadImg={handleImageUpload}
          onSave={saveNote}
        />

        {/* 评论侧边栏 */}
        {showComments && noteId && (
          <div className="w-[380px] h-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 overflow-auto">
            <div className="p-4">
              <CommentSection
                noteId={Number(noteId)}
                onCommentUpdate={() => loadCommentCount(Number(noteId))}
              />
            </div>
          </div>
        )}
      </div>

      {/* Emoji选择器 */}
      <EmojiSelect
        isSelect={isSelectEmoji}
        onSelectChange={onSelectChange}
        setEmoji={handleEmojiSelect}
      />

      {/* 新建标签对话框 */}
      <Modal
        isOpen={isOpenCreateTag}
        onOpenChange={onOpenChangeCreateTag}
        backdrop="blur"
        placement="center"
        size="sm"
      >
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1 text-center">
                创建新标签
              </ModalHeader>
              <ModalBody>
                <Input
                  autoFocus
                  label="标签名称"
                  placeholder="输入标签名称"
                  variant="bordered"
                  value={newTagName}
                  onValueChange={setNewTagName}
                  startContent={<BiTag className="text-default-400" />}
                />
              </ModalBody>
              <ModalFooter className="justify-center">
                <Button color="default" variant="flat" onPress={onClose} disabled={creatingTag}>
                  取消
                </Button>
                <Button color="primary" onPress={handleSubmitNewTag} isLoading={creatingTag}>
                  创建
                </Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
} 